package cn.edu.ncut.cs.springboot.springbootdatabase.config;

import cn.edu.ncut.cs.springboot.springbootdatabase.service.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    private final CustomUserDetailsService customUserDetailsService;

    public SecurityConfig(CustomUserDetailsService customUserDetailsService) {
        this.customUserDetailsService = customUserDetailsService;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorizeRequests ->
                        authorizeRequests
                                .requestMatchers("/admin").hasRole("ADMIN")
                                .requestMatchers("/admin/books/**").hasRole("ADMIN")  // 只有 ADMIN 角色可以访问书目管理接口
                                .requestMatchers("/librarian/**").hasRole("LIBRARIAN")
                                .requestMatchers("/user/**").hasRole("USER")
                                .anyRequest().permitAll() // 允许其他请求不进行权限验证
                )

                .formLogin(form -> form
                        .loginPage("/login") // 登录页面的 URL
                        .successHandler((request, response, authentication) -> {
                            // 获取当前用户的角色
                            String role = authentication.getAuthorities().stream()
                                    .map(grantedAuthority -> grantedAuthority.getAuthority())
                                    .findFirst()
                                    .orElse("");

                            // 根据角色跳转到不同页面
                            if (role.equals("ROLE_ADMIN")) {
                                response.sendRedirect("/admin"); // 如果是管理员，跳转到 /admin
                            } else if (role.equals("ROLE_LIBRARIAN")) {
                                response.sendRedirect("/librarian"); // 如果是图书管理员，跳转到 /librarian
                            } else if (role.equals("ROLE_USER")) {
                                response.sendRedirect("/user"); // 如果是普通用户，跳转到 /user
                            } else {
                                response.sendRedirect("/"); // 默认跳转到首页
                            }
                        })
                        .permitAll() // 允许所有人访问登录页面
                )
                .logout(logout -> logout.permitAll()) // 允许所有人注销
                .csrf(csrf -> csrf.disable()); // 禁用 CSRF（根据需要启用或禁用）
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance(); // 使用明文密码（不进行加密）
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(customUserDetailsService); // 使用自定义的 UserDetailsService
        provider.setPasswordEncoder(passwordEncoder()); // 配置明文密码编码器
        return provider;
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
        builder.authenticationProvider(authenticationProvider());
        return builder.build();
    }
}



//package cn.edu.ncut.cs.springboot.springbootdatabase.config;
//
//import cn.edu.ncut.cs.springboot.springbootdatabase.service.CustomUserDetailsService;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
//import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.crypto.password.NoOpPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.security.web.SecurityFilterChain;
//
//@Configuration
//public class SecurityConfig {
//
//    private final CustomUserDetailsService customUserDetailsService;
//
//    public SecurityConfig(CustomUserDetailsService customUserDetailsService) {
//        this.customUserDetailsService = customUserDetailsService;
//    }
//
//    @Bean
//    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
//        http
//                .authorizeHttpRequests(authorizeRequests ->
//                        authorizeRequests
////                                .requestMatchers("/admin/**").hasRole("ADMIN")
//                                .requestMatchers("/admin").hasRole("ADMIN")
//                                .requestMatchers("/librarian/**").hasRole("LIBRARIAN")
//                                .requestMatchers("/user/**").hasRole("USER")
//                                .anyRequest().permitAll()
//                )
//                .formLogin(form -> form
//                        .loginPage("/login")
//                        .defaultSuccessUrl("/admin")
//                        .permitAll()
//                )
//                .logout(logout -> logout.permitAll())
//                .csrf(csrf -> csrf.disable()); // 禁用 CSRF（根据需要启用或禁用）
//        return http.build();
//    }
//
//    @Bean
//    public PasswordEncoder passwordEncoder() {
//        return NoOpPasswordEncoder.getInstance(); // 使用明文密码
//    }
//
//    @Bean
//    public DaoAuthenticationProvider authenticationProvider() {
//        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
//        provider.setUserDetailsService(customUserDetailsService); // 使用自定义的 UserDetailsService
//        provider.setPasswordEncoder(passwordEncoder()); // 配置明文密码编码器
//        return provider;
//    }
//
//    @Bean
//    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
//        AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
//        builder.authenticationProvider(authenticationProvider());
//        return builder.build();
//    }
//}
//
//
//
//
